﻿using System;
using System.Drawing;
using RaytracerLib.Layers;
using RaytracerLib.MathLib;
using TomanuExtensions;
using YAXLib;

namespace RaytracerLib.Postprocessing.LightCorrector
{
    public class ScaleAllLinearToneMapper : ToneMapper
    {
        private ScaleEachPixelToneMapper m_adj = new ScaleEachPixelToneMapper();

        [YAXOnDeserialized]
        private void OnDeserialized()
        {
            m_adj = new ScaleEachPixelToneMapper();
        }

        internal override void Postprocess(Rectangle a_src_rect, ColorArrayFloat a_ar)
        {
            m_adj.Postprocess(a_src_rect, a_ar);
        }

        internal override void PostprocessFinalize(ColorArrayFloat a_ar)
        {
            float m = 0;

            foreach (var p in a_ar.Pixels())
            {
                ColorFloat c = a_ar.GetColor(p.X, p.Y);
                m = Math.Max(m, c.R);
                m = Math.Max(m, c.G);
                m = Math.Max(m, c.B);
            }

            if (m > 1)
            {
                foreach (var p in a_ar.Pixels())
                {
                    ColorFloat c = a_ar.GetColor(p.X, p.Y);
                    c = new ColorFloat(c.R / m, c.G / m, c.B / m);
                    a_ar.SetColor(p.X, p.Y, c);
                }
            }
        }

        public override bool RequiredPostprocessingFinalization
        {
            get
            {
                return true;
            }
        }
    }
}